import { defineConfig, loadEnv } from 'vite';
import path from 'node:path';
import uni from '@dcloudio/vite-plugin-uni';
import AutoImport from 'unplugin-auto-import/vite';
import eslintPlugin from 'vite-plugin-eslint';
import UniManifest from '@uni-helper/vite-plugin-uni-manifest';
import UniPages from '@uni-helper/vite-plugin-uni-pages';
import UniLayouts from '@uni-helper/vite-plugin-uni-layouts';

// https://vitejs.dev/config/
export default async ({ mode }) => {
  const UnoCSS = (await import('unocss/vite')).default;
  const { UNI_PLATFORM } = process.env;

  const env = loadEnv(mode, path.resolve(process.cwd(), 'env'));
  const { VITE_APP_PORT, VITE_DELETE_CONSOLE, VITE_SHOW_SOURCEMAP } = env;

  return defineConfig({
    plugins: [
      UniLayouts(),
      UniPages({
        dts: false
      }),
      UniManifest(),
      uni(),
      UnoCSS(),
      AutoImport({
        imports: ['vue', 'uni-app', 'pinia'],
        dts: false,
        eslintrc: {
          enabled: true,
          filepath: './.eslintrc-auto-import.mjs'
        }
      }),
      // eslint插件配置
      eslintPlugin({
        include: ['src/**/*.js', 'src/**/*.ts', 'src/**/*.vue'], // 指定需要检查的文件
        exclude: ['node_modules/**', 'src/uni_modules/**', 'dist/**'], // 指定不需要检查的文件
        fix: false, // 是否自动修复
        cache: true // 是否启用缓存
      })
    ],

    define: {
      __UNI_PLATFORM__: JSON.stringify(UNI_PLATFORM)
    },
    server: {
      host: '0.0.0.0',
      hmr: true,
      port: Number.parseInt(VITE_APP_PORT, 10),
      // 仅 H5 端生效，其他端不生效（其他端走build，不走devServer)
      proxy: undefined
    },
    resolve: {
      alias: {
        '@': path.join(process.cwd(), './src')
      }
    },

    build: {
      // 方便非h5端调试
      sourcemap: VITE_SHOW_SOURCEMAP === 'true', // 默认是false
      target: 'es6',
      // 开发环境不用压缩
      minify: mode === 'development' ? false : 'terser',
      terserOptions: {
        compress: {
          drop_console: VITE_DELETE_CONSOLE === 'true',
          drop_debugger: true
        }
      }
    }
  });
};
